
package com.ifcar.app.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

public class ScrollTabs extends HorizontalScrollView {
    private View mLeftView;

    private View mRightView;

    public ScrollTabs(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ScrollTabs(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollTabs(Context context) {
        super(context);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        checkScrollX();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        checkScrollX();
    }

    private void checkScrollX() {
        View child = getChildAt(0);
        if (child == null) {
            setViewVisibility(mLeftView, View.INVISIBLE);
            setViewVisibility(mRightView, View.INVISIBLE);
            return;
        }

        int scrollX = getScrollX();
        if (scrollX <= 0) {
            setViewVisibility(mLeftView, View.INVISIBLE);
        } else {
            setViewVisibility(mLeftView, View.VISIBLE);
        }

        int maxScrollX = child.getRight() + getPaddingRight() - getWidth();
        if (scrollX >= maxScrollX) {
            setViewVisibility(mRightView, View.INVISIBLE);
        } else {
            setViewVisibility(mRightView, View.VISIBLE);
        }
    }

    private void setViewVisibility(View v, int visibility) {
        if (v != null) {
            v.setVisibility(visibility);
        }
    }

    public void setLeftView(View left) {
        mLeftView = left;
    }

    public void setRightView(View Right) {
        mRightView = Right;
    }

    public void scrollToLeft() {
        scrollTo(0, 0);
    }

    public void scrollToRight() {
        View child = getChildAt(0);
        if (child == null) {
            return;
        }
        int maxScrollX = child.getRight() + getPaddingRight() - getWidth();
        scrollTo(maxScrollX, 0);
    }
    
    
    public void scrollToPosition(int position) {
        ViewGroup child = (ViewGroup)getChildAt(0);
        if (child == null) {
            return;
        }
        if (position < 0 || position >= child.getChildCount()) {
            return;
        } if (position == 0) {
            scrollToLeft();
        } else if (position == child.getChildCount() - 1) {
            scrollToRight();
        } else {
            View item = child.getChildAt(position);
            int left = Math.min(item.getLeft(), child.getRight() - getWidth());
            scrollTo(left, 0);
        }
    }
}
